import md5 from 'md5';
import { storageToken } from '~/logic';
import { message } from 'ant-design-vue';
import { sendMessage } from 'webext-bridge';
// import html2canvas from 'html2canvas';
import sha1 from 'crypto-js/sha1';
import { EXT_SET_USER_TOKEN } from '~/events';

const RESUME_SOURCE: {
  [key: string]: {
    selector: string;
    platform: string;
    _platform: string;
  };
} = {
  zhipin: {
    selector: '.resume-container.resume-online-hide-tip',
    platform: 'BOSS直聘',
    _platform: 'zhipin',
  },
  zhaopin: {
    selector: '.km-skeleton.km-skeleton--has-avatar.km-skeleton--loading+div',
    platform: '智联招聘',
    _platform: 'zhaopin',
    // ok
  },
  '51job': {
    platform: '前程无忧',
    selector: '.pageTag+table',
    _platform: '51job',
    // ok
  },
  'lpt.liepin': {
    selector: '.water-mark-wrap',
    platform: '猎聘',
    _platform: 'liepin',
  },
  [`h.liepin.com`]: {
    selector: '.c-resume-body-cont',
    platform: '猎聘猎头',
    _platform: 'liepin',
    // ok
  },
};

type TYPE_KEY_OF_RESUME_SOURCE = keyof typeof RESUME_SOURCE;

export function makeEncry(str: string): string {
  return md5(md5(str));
}

// 在 background 调用接口后 catch 到的错误进行处理提示
export function makeContentLogout(error: any) {
  if (error.status === 401) {
    message.error(`登录状态过期，请刷新页面后重新登录！`);
    storageToken.value = null;
    sendMessage(EXT_SET_USER_TOKEN, { token: null });
  }
}

function hashHtml(html: string): string {
  const str = encodeURIComponent(html);
  return str;
}

function makeHashId(text: string) {
  return sha1(text).toString();
}

export async function getDomHtml(href: string) {
  const keys = Object.keys(RESUME_SOURCE);
  const key = keys.find(t => href.indexOf(t) > -1);
  if (!key) {
    message.error(`当前页面非已知简历页，请联系管理员添加！`);
    return false;
  }
  const item = RESUME_SOURCE[key as TYPE_KEY_OF_RESUME_SOURCE];
  const ele = document.querySelector(item.selector) as HTMLElement;
  if (!ele) {
    message.error(`${item.platform}未找到对应简历页标识，请联系管理员添加！`);
    return false;
  }
  const html = ele.innerHTML;
  const text = (ele as HTMLElement).innerText;

  // const blob = await html2canvas(ele, {
  //   scale: 0.8,
  //   useCORS: true,
  //   imageTimeout: 2000000,
  //   height: ele.offsetHeight,
  //   width: ele.offsetWidth,
  // });
  // const h = blob.toDataURL();
  // const img = new Image();
  // const win = window.open('', '_blank')!;
  // img.src = h;
  // win.document.write(img.outerHTML);
  // win.document.title = '查看图片';
  // win.document.close();

  return {
    html: hashHtml(html),
    platform: item._platform,
    hashId: makeHashId(text),
    pdfHtml: '',
  };
}
